#include "Server.h"

#include <iostream>
#include <boost\thread.hpp>
#include <boost\bind.hpp>

using namespace std;
using namespace boost::asio;

Server::Server(string servername):pop3(110, servername), smtp(25, servername), control(8000, servername), name(servername)
{
}


Server::~Server(void)
{
}

//Startet den SMTP- und POP3-Socket
void Server::run()
{
	//smtp.run();
	threads.create_thread(boost::bind(&ServerSocket::run, &smtp));
	//only test
	//boost::this_thread::sleep(boost::posix_time::milliseconds(500));
	threads.create_thread(boost::bind(&ServerSocket::run, &pop3));
	threads.create_thread(boost::bind(&ServerSocket::run, &control));
}
//Soll die Socket-Threads beenden.
void Server::stop()
{
	
	smtp.stop();
	stopSocket(25);
	
	pop3.stop();
	stopSocket(110);
	
	control.stop();
	stopSocket(8000);
	
	cout << "Warte, bis alle Sockets beendet sind" << endl;
	threads.join_all();

	cout << "Alle Sockets beendet" << endl;
}

void Server::stopSocket(unsigned short port)
{
	string localhost = "127.0.0.1";
	string dummy = "-1";
	io_service io_service;
	ip::tcp::endpoint server(ip::address::from_string(localhost), port);
	ip::tcp::socket socket(io_service);
	socket.connect(server);
	//boost::system::error_code ignored_error;
	socket.write_some(boost::asio::buffer(dummy,dummy.length()));
	
	boost::this_thread::sleep(boost::posix_time::milliseconds(500));
	socket.close();
}